package DiningPhilosophersProblem;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2022-12-28
 * Time: 8:26
 */

public class Philosophers extends Thread{
    private Chopstick left;//左手筷子
    private Chopstick right;//右手筷子

    public Philosophers(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while(true) {
            synchronized (left) { //先拿左手筷子
                synchronized (right) { //在拿右手筷子
                    eat();//然后吃饭
                }
            }
        }
    }

    private void eat() {
        System.out.println(Thread.currentThread() + "eating...");
        try {
            Thread.sleep(1000);//思考1s钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}